<template>
	<view>
		<view class="title">
			<view class="box">
				<image @click="clickBack" class="backIcon" src="../static/backBlack.png"></image>
				<view class="text">{{title}}</view>
			</view>
		</view>
		<view class="numberBox">
			<view class="number">{{1}}</view>
			<view class="textBox">
				<view class="textBoxtop">
					<view class="text1">号桌</view>
					<view class="text2">空闲</view>
				</view>
				<view class="text3">默认就近一小时开台</view>
			</view>
		</view>
		<view class="cardBox">
			<view class="stroke" :class="{trueCard:cardChouse==item}" @click="chouse_package(item)" v-for="item in 1">
				<view class="background">
					<view class="card">
						<view class="text1">立即开台</view>
						<view class="text2">{{data.dom.price}}元/小时</view>
					</view>
				</view>
			</view>
		</view>
		<view class="time_view flex justify-between align-center">
			<scroll-view class="scroll-view_H" scroll-x="true">
				<view class="scroll-view-item_H" :class="[index == data.dateChouseIndex ? 'alive' : 'scroll-view-item_H']"
					v-for="(item,index) in data.weekDates" :key="index" @click="clcick_date(item,index)">
					<view class="flex flex-direction justify-center align-center">
						<!-- <text>今天</text> -->
						<text>{{item.strTime}}</text>
					</view>
				</view>

			</scroll-view>
			<image class="image" src="../static/日历.png"></image>
		</view>

		<view class="playTimeListBox">
			<view class="listTitle">
				<view class="text1">选时间</view>
				<view class="text2">价格：{{data.dom.price}}/小时</view>
			</view>
			<scroll-view class="list" scroll-y="true">
				<view class="listBox">
					<view class="card" @click="click_time(item)" :class="{trueListCard:timeId.indexOf(item)!==-1}"
						v-for='item in 24'>
						<view class="text1">空闲中</view>
						<view class="text2">{{item-1>9?null:'0'}}{{item-1}}:00-{{item>9?null:'0'}}{{item}}:00</view>
					</view>
				</view>
			</scroll-view>
		</view>
		<view class="bottom">
			<view class="bottomTitle">已选时间</view>
			<view class="flex justify-between align-center">
				<view class="allTime">10月27 {{allTime.begin_time}} <text
						v-if="allTime.begin_time && allTime.begin_time">-</text> {{allTime.end_time}}</view>
				<view class="setTimeBox">
					<image @click="addOrsubtractTime('subtract')" class="subtractTime" src="../static/减少时间.png" mode="">
					</image>
					<view class="text">{{allTime.total}}小时</view>
					<image @click="addOrsubtractTime('add')" class="addTime" src="../static/增加时间.png" mode=""></image>
				</view>
			</view>
			<view class="flex justify-between align-center margin-top-sm">
				<view class="allMoney">¥ {{money.toFixed(2)}} 元</view>
				<view class="orders" @click="click_orders">立即下单</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		formatTime
	} from "@/utils/dateUtil.js"
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		reactive,
		ref,
		getCurrentInstance
	} from 'vue';
	let {
		proxy
	} = getCurrentInstance()
	let data = reactive({
		options: {},
		dom: {},
		weekDates: [], //近一周日期数据
		dateChouseIndex: 0,
		timeAll: [],
		filterTimeAll: [],
		currentTime: 0,
		storeDom: null,
		userIfon: null,
		days: "",
		timeLeft: 6, // 假设计时时间为60秒
		timer: null, // 计时器
		reservationResult: {}
	})
	const timeId = ref([])
	// const dateChouseIndex = ref(-1)
	const clcick_date = (item, index) => {
		data.days = item.newTime
		console.log(item, 'item')
		data.dateChouseIndex = index
		// dateChouseId.value = item
	}
	const cardChouse = ref(1)
	const chouse_package = (item) => {
		cardChouse.value = item
	}

	function sortChange(a, b) {
		return a - b;
	}

	function generateTimeRangesFromCurrentTime() {
		const ranges = [];
		const now = new Date();
		const currentHour = data.currentTime;
		// now.getHours()
		for (let i = currentHour; i < 24; i++) {
			const startHour = i < 10 ? `0${i}` : `${i}`;
			const endHour = (i + 1) < 10 ? `0${i + 1}` : `${i + 1}`;
			const timeRange = `${startHour}:00-${endHour}:00`;
			// const date = new Date(now.getFullYear(), now.getMonth(), now.getDate(), i, 0, 0);
			ranges.push({
				timeRange,
				id: Date.now() + '' + i
				// date
			});
		}
		return ranges;
	}
	const allTime = ref({
		total: 0,
		begin_time: "",
		end_time: "",
	})
	const money = ref(0)

	const click_time = (item) => {
		console.log(item)
		let index = timeId.value.indexOf(item)
		if (index !== -1) {
			timeId.value.splice(index, 1)
			timeId.value.sort(sortChange)
		} else {
			timeId.value.push(item)
			let newArray = arrayHelperFunction(timeId.value, timeId.value.length)
			timeId.value = newArray
		}
		allTime.value.total = timeId.value.length
		allTime.value.BandE = ''
		let farsttime = timeId.value[0]
		let endtime = timeId.value[timeId.value.length - 1]
		money.value = timeId.value.length * data.dom.price
		console.log(farsttime, endtime)
		if (timeId.value.length > 0) {
			if (timeId.value.length < 2) {
				allTime.value.begin_time = `${farsttime-1>9?'':'0'}${farsttime-1}:00`
				allTime.value.end_time = `${farsttime>9?'':'0'}${farsttime}:00`
			} else {
				allTime.value.begin_time = `${farsttime>9?'':'0'}${farsttime-1}:00`
				allTime.value.end_time = `${endtime>9?'':'0'}${endtime}:00`
			}
			console.log(allTime.value, 'allTime')
			return
		} else {
			allTime.value.begin_time = ""
			allTime.value.end_time = ""
		}

	}
	const addOrsubtractTime = (item) => {
		if (item == 'add' && allTime.value.total !== 24) {
			if (allTime.value.total == 0) {
				click_time(1)
			} else {
				click_time(timeId.value[timeId.value.length - 1] + 1)
			}
			return
		}
		if (item == 'subtract') {
			if (allTime.value.total !== 0) {
				click_time(timeId.value[timeId.value.length - 1])
			}
			return
		}
	}
	const arrayHelperFunction = (array, lenght) => {
		if (lenght !== array[lenght - 1]) {
			let first = array[0]
			let end = array[lenght - 1]
			let interval = end - first - 1
			const arr = [...new Array(end + 1).keys()]
			arr.splice(0, first)
			// arr.push(end)
			return arr
		}
		return array
	}
	const clickBack = () => {
		const pages = getCurrentPages();
		if (pages.length > 1) {
			uni.navigateBack({
				delta: 1
			});
		} else {
			// 这里可以做一些其他逻辑，比如提示用户已经是首页等操作
			uni.reLaunch({
				url: '/pages/home/index'
			});
		}
	}

	function calculateSeconds(begin_time, end_time) {
		const start = new Date(begin_time).getTime(); // 将开始时间转换为毫秒
		const end = new Date(end_time).getTime(); // 将结束时间转换为毫秒
		const seconds = (end - start) / 1000; // 计算秒数差，毫秒转换为秒
		return seconds
	}

	function startCountdown() {
		if (data.timer) return; // 如果计时器已经存在，则不创建
		data.timer = setInterval(() => {
			if (data.timeLeft > 0) {
				data.timeLeft -= 1;
				console.log(data.timeLeft)
			} else {
				reservation_end()
				clearCountdown(); // 时间到了，清除计时器
				// uni.showModal({
				// 	title: '提示',
				// 	content: '时间已到',
				// 	showCancel: false,
				// });
			}
		}, 1000);
	}

	function clearCountdown() {
		clearInterval(data.timer);
		data.timer = null;
		data.timeLeft = 6
	}

	function reservation_end() {
		proxy.$https('/reservation_end_api', {
			order_number: data.reservationResult.order_number,
			user_id: data.userIfon.user_id,
			store_id: data.dom.store_id,
			binding_status: data.reservationResult.binding_status,
			device_id: data.reservationResult.device_id,
			actual_payment: data.reservationResult.actual_payment,
			payment_method: data.reservationResult.payment_method,
		}).then(res => {
			uni.showToast({
				title: '订单结束',
				icon: "success"
			})
		})
	}
	const click_orders = () => {
		let beginDateStr = `${data.days} ${allTime.value.begin_time}`
		let endDateStr = `${data.days} ${allTime.value.end_time}`
		const beginDate = new Date(beginDateStr.replace(' ', 'T'));
		const endDate = new Date(endDateStr.replace(' ', 'T'));
		proxy.$https('/reservation_generate_api', { //预约单生成
			user_id: data.userIfon.user_id, //用户id
			user_name: data.userIfon.user_name, //用户名
			user_phone: data.userIfon.phone, //用户电话
			user_avatar: data.userIfon.avatar, //用户头像
			store_id: data.dom.store_id, //商家id
			store_name: data.storeDom.store_name,
			store_phone: data.storeDom.boss_phone,
			store_avatar: data.storeDom.store_avatar,
			province: data.storeDom.province,
			city: data.storeDom.city,
			district: data.storeDom.district,
			binding_id: data.dom.binding_id,
			begin_time: beginDate.getTime(),
			end_time: endDate.getTime(),
			discount_amount: money.value,
		}).then(result => {
			console.log(result, 'end_time')
			data.reservationResult = result
			reservation_end()
			// data.timeLeft = calculateSeconds(beginDate, endDate)
			// startCountdown()
			uni.showToast({
				title: '下单成功',
				icon: "success"
			})
		})

	}
	const title = ref('')

	function getWeekDates() { //获取近一周数据
		const today = new Date();
		const startDate = new Date(today); // 设置起始日期为今天
		const endDate = new Date(today); // 设置结束日期为今天之后的一周
		endDate.setDate(endDate.getDate() + 6); // 加上6天
		const weekDates = [];
		let currentDate = startDate;
		while (currentDate <= endDate) {
			weekDates.push({
				strTime: formatDate(currentDate),
				newTime: formatDateY(currentDate),
			});
			currentDate.setDate(currentDate.getDate() + 1); // 将当前日期设置为下一天
		}
		return weekDates;
	}

	function formatDate(date) { //年月日
		const month = (date.getMonth() + 1).toString().padStart(2, '0');
		const day = date.getDate().toString().padStart(2, '0');
		return `${month}-${day}`;
	}

	function formatDateY(date) { //年月日
		const year = date.getFullYear();
		const month = (date.getMonth() + 1).toString().padStart(2, '0');
		const day = date.getDate().toString().padStart(2, '0');
		return `${year}-${month}-${day}`;
	}

	function info(res) {
		proxy.$https('/get_binding_message_api', { //获取产品绑定信息
			store_id: data.options.store_id,
			binding_id: data.options.binding_id
		}).then(result => {
			data.dom = result.binding_message[0]
			console.log(result, 'res')
		})
	}

	function storeInfo() {
		proxy.$https('/store_details_api', {
			store_id: data.options.store_id,
		}).then(result => {
			data.storeDom = result.atlas[0]
			console.log(result, 'res', data.storeDom)
		})
	}

	function generateCurrentDate() {
		const today = new Date();
		const year = today.getFullYear();
		const month = String(today.getMonth() + 1).padStart(2, '0');
		const day = String(today.getDate()).padStart(2, '0');
		data.days = `${year}-${month}-${day}`;
	}
	onLoad((option) => {
		data.options = option.item ? JSON.parse(decodeURIComponent(option.item)) : {};
		data.weekDates = getWeekDates()
		data.timeAll = generateTimeRangesFromCurrentTime()
		data.userIfon = getApp().globalData.userIfon
		info()
		storeInfo()
		generateCurrentDate()
	})
</script>

<style lang="scss" scoped>
	.title {
		width: 100vw;
		height: 550rpx;
		background-image: url('../static/背景.png');
		background-size: 100% 100%;

		.box {
			display: flex;
			flex-direction: row;
			width: 100vw;
			height: auto;
			padding-top: 110rpx;

			.backIcon {
				position: absolute;
				left: 20rpx;
				z-index: 99;
				height: 40rpx;
				width: 40rpx;
			}

			.text {
				text-align: center;
				width: 100vw;
				height: 44rpx;
				font-weight: bold;
				font-size: 32rpx;
				color: #333333;
				line-height: 38rpx;
			}
		}

	}

	.numberBox {
		height: auto;
		width: 100vw;
		position: relative;
		position: absolute;
		top: 194rpx;
		left: 30rpx;
		display: flex;
		align-items: center;

		.number {
			width: 60rpx;
			height: 112rpx;
			font-family: PingFang SC, PingFang SC;
			font-weight: bold;
			font-size: 100rpx;
			color: #333333;
			line-height: 117rpx;
			text-align: left;
			font-style: normal;
			text-transform: none;
		}

		.textBox {
			margin-left: 8rpx;

			.textBoxtop {
				display: flex;

				.text1 {
					font-weight: bold;
					font-size: 30rpx;
					color: #333333;
					line-height: 35rpx;
				}

				.text2 {
					margin-left: 12rpx;
					width: 106rpx;
					height: 38rpx;
					border-radius: 19rpx 19rpx 19rpx 19rpx;
					border: 1rpx solid #10C76E;

					font-weight: 400;
					font-size: 22rpx;
					color: #10C76E;
					line-height: 38rpx;
					text-align: center;
				}
			}

			.text3 {
				margin-top: 8rpx;
				font-weight: 400;
				font-size: 24rpx;
				color: #333333;
				line-height: 28rpx;
			}
		}
	}

	.cardBox {
		position: relative;
		position: absolute;
		top: 338rpx;
		left: 36rpx;
		display: flex;

		.stroke {
			border-radius: 20rpx;
			padding: 2rpx;
			margin-right: 20rpx;

			// background: linear-gradient(137deg, rgba(63, 247, 158, 1), rgba(16, 199, 110, 1));
			.background {
				background: #FFFFFF;
				border-radius: 20rpx;
			}

			.card {
				width: 212rpx;
				height: 198rpx;
				background: #FFFFFF;
				border-radius: 20rpx;
				border: 2rpx solid #D9D9D9;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;

				.text1 {
					font-weight: bold;
					font-size: 36rpx;
					color: #666666;
					line-height: 42rpx;
				}

				.text2 {
					margin-top: 14rpx;
					font-weight: 400;
					font-size: 24rpx;
					color: #666666;
					line-height: 28rpx;
				}

			}
		}

		.trueCard {
			background: linear-gradient(137deg, rgba(63, 247, 158, 1), rgba(16, 199, 110, 1));

			.background {
				background: #FFFFFF;
				border-radius: 20rpx;
			}

			.card {
				background: rgba(16, 199, 110, 0.11);

				.text1 {
					font-weight: bold;
					font-size: 36rpx;
					color: #059E54;
					line-height: 42rpx;
				}

				.text2 {
					font-weight: 400;
					font-size: 24rpx;
					color: #059E54;
					line-height: 28rpx;

				}

			}
		}
	}

	.playTimeListBox {
		position: absolute;
		top: 708rpx;
		left: 32rpx;

		.listTitle {
			display: flex;

			.text1 {
				width: 84rpx;
				height: 40rpx;
				font-weight: bold;
				font-size: 28rpx;
				color: #333333;
				line-height: 28rpx;
			}

			.text2 {
				margin-left: 20rpx;
				width: 196rpx;
				height: 34rpx;
				font-weight: 400;
				font-size: 24rpx;
				color: #666666;
				line-height: 32rpx;
			}
		}

		.list {
			height: 530rpx;
			margin-top: 10rpx;

			.listBox {
				display: grid;
				grid-template-columns: 236rpx 236rpx 214rpx;

				.card {
					margin-top: 10rpx;
					margin-bottom: 10rpx;
					width: 214rpx;
					height: 100rpx;
					background: rgba(16, 199, 110, 0.1);
					border-radius: 8rpx 8rpx 8rpx 8rpx;
					display: flex;
					flex-direction: column;
					justify-content: center;
					align-items: center;

					.text1 {
						width: 72rpx;
						height: 34rpx;
						font-weight: 400;
						font-size: 24rpx;
						color: #10C76E99;
						line-height: 34rpx;
					}

					.text2 {
						margin-top: 4rpx;
						width: 144rpx;
						height: 34rpx;
						font-weight: bold;
						font-size: 24rpx;
						color: #10C76E99;
						line-height: 34rpx;
					}
				}

				.trueListCard {
					background: #10C76E;

					.text1,
					.text2 {
						color: #FFFFFF;
					}
				}
			}
		}

	}

	.bottom {
		position: relative;
		position: absolute;
		bottom: 0;
		width: 750rpx;
		background: #FFFFFF;
		box-shadow: 0rpx -2rpx 20rpx 0rpx rgba(0, 0, 0, 0.06);
		border-radius: 40rpx 40rpx 0rpx 0rpx;
		padding: 32rpx;

		.bottomTitle {
			width: 112rpx;
			height: 40rpx;
			font-weight: bold;
			font-size: 28rpx;
			color: #333333;
			line-height: 33rpx;
		}

		.allTime {
			width: 230rpx;
			height: 34rpx;
			font-weight: 400;
			font-size: 24rpx;
			color: #666666;
			line-height: 28rpx;
		}

		.setTimeBox {

			right: 46rpx;
			top: 46rpx;
			display: flex;
			align-items: center;

			.subtractTime {
				height: 56rpx;
				width: 56rpx;
			}

			.text {
				// width: 74rpx;
				height: 40rpx;
				font-weight: bold;
				font-size: 28rpx;
				color: #333333;
				line-height: 40rpx;
				margin-left: 18rpx;
				margin-right: 18rpx;
			}

			.addTime {
				height: 56rpx;
				width: 56rpx;
			}
		}

		.allMoney {
			width: 242rpx;
			height: 96rpx;
			font-weight: 400;
			font-size: 40rpx;
			color: #EE5618;
			line-height: 47rpx;
		}

		.orders {
			top: 182rpx;
			right: 40rpx;
			width: 216rpx;
			height: 68rpx;
			background: #10C76E;
			box-shadow: 0rpx 0rpx 40rpx 0rpx rgba(255, 255, 255, 0.25);
			border-radius: 40rpx 40rpx 40rpx 40rpx;
			border: 2rpx solid rgba(16, 199, 110, 0.3);

			font-weight: 600;
			font-size: 32rpx;
			color: #FFFFFF;
			line-height: 68rpx;
			text-shadow: 0px 2px 0px rgba(0, 0, 0, 0.1);
			text-align: center;
		}
	}

	.time_view {
		padding: 0 32rpx;

		.scroll-view_H {
			white-space: nowrap;
			width: calc(100% - 100rpx);

			// margin-top: 20rpx;
			.scroll-view-item_H {
				display: inline-block;
				width: 108rpx;
				height: 108rpx;
				background: #fff;
				border-radius: 12rpx 12rpx 12rpx 12rpx;
				// padding: 18rpx 0;
				line-height: 108rpx;
				font-family: PingFang SC, PingFang SC;
				font-weight: 400;
				font-size: 24rpx;
				color: #666666;

				&:not(:first-child) {
					margin-left: 8rpx;
				}
			}

			.alive {
				width: 108rpx;
				height: 108rpx;
				background: #10C76E;
				border-radius: 8rpx 8rpx 8rpx 8rpx;
				font-family: PingFang SC, PingFang SC;
				font-weight: 400;
				font-size: 24rpx;
				color: #FFFFFF;
			}


		}

		.image {
			height: 68rpx;
			width: 68rpx;
			// margin-left: 18rpx;
			// margin-top: 20rpx;
		}
	}
</style>